﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Yugi.Client.Card.Load
{
    public class LoadManager : ILoad
    {
        #region ILoad Members

        public event EventHandler Complete;

        public bool IsParallel
        {
            get
            {
                return false;
            }
        }
        private List<ILoad> parallel = new List<ILoad>();
        private int parellel_count;
        private List<ILoad> schedule = new List<ILoad>();
        public void Add(ILoad item)
        {
            if (item.IsParallel)
                parallel.Add(item);
            else
                schedule.Add(item);
        }
        public void Load(object state)
        {
            if (parallel.Count != 0)
            {
                // Parallel Load
                parellel_count = parallel.Count;
                foreach (ILoad item in parallel)
                {
                    item.Complete += new EventHandler(item_Complete);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(item.Load),state);
                }
            }
            // Schedule Load
            foreach (ILoad item in schedule)
            {
                item.Load(state);
            }
            // Wait For Parallel Complete
            while (true)
            {
                if (parellel_count == 0)
                    break;
                else
                    Thread.Sleep(20);
            }

            if (Complete != null) Complete(this, new EventArgs());
        }

        void item_Complete(object sender, EventArgs e)
        {
            ILoad obj = sender as ILoad;
            obj.Complete -= new EventHandler(item_Complete);
            lock (this)
            {
                this.parellel_count--;
            }
        }

        #endregion
        
    }
}
